<template>
  <div>
    <el-upload
      ref="fileUpload"
      class="upload-demo"
      action="string"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="handleBeforeUpload"
      :before-remove="beforeRemove"
      :http-request="httpRequest"
      multiple
      :limit="limit"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :on-change="handleChange"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize">
          大小不超过
          <b style="color: #f56c6c">{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          格式为
          <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
        </template>
        的文件
      </div>
    </el-upload>
    <el-progress :percentage="videoUploadPercent" style="width:100%" v-if="videoFlag"></el-progress>
  </div>
</template>
<script>

import moment from "moment"
import { FileEnum } from "@/utils/yun"
import { OSSClient } from "@/utils/ossConfig/config"

import axios from 'axios'

export default {
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    model: {
      type: String,
      default: FileEnum.SHORT_VIDEO
    }
  },
  data () {
    return {
      fileList: [],
      videoFlag: false,
      videoUploadPercent: 0,
    }
  },
  computed: {
    // 是否显示提示
    showTip () {
      return this.isShowTip && (this.fileType || this.fileSize)
    },
  },
  watch: {
    value: {
      handler (val) {
        if (this.$yun.stringIsNotEmpty(val)) {
          if (this.$refs.fileUpload && this.listToString(this.$refs.fileUpload.$data.uploadFiles) == val) return
          let temp = 1
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',')
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item.split('/').pop(), previewUrl: item }
            }
            item.uid = item.uid || new Date().getTime() + temp++
            return item
          })
        } else {
          this.fileList = []
          return []
        }
      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    httpRequest (e) {
      this.videoFlag = true
      let file = e.file // 文件信息
      if (!file) {
        return false
      }
      let _this = this
      let lastIndex = file.name.lastIndexOf(".")
      let result = file.name.substring(0, lastIndex)
      let date = moment().format("YYYY-MM-DD")
      let aliyunFileKey = this.model + '/' + date + '/' + new Date().getTime() + parseInt(Math.random() * (9999 - 1000 + 1) + 1000, 10)
      OSSClient.putObject({
        Bucket: process.env.VUE_APP_OSS_BUCKET,
        Region: process.env.VUE_APP_OSS_REGION,
        Key: aliyunFileKey,
        StorageClass: 'STANDARD',
        Body: file,
        onProgress: function (info) {
          let infoPercent = JSON.parse(JSON.stringify(info))
          _this.videoUploadPercent = infoPercent.percent * 100
          if (_this.videoUploadPercent == 100) {
            _this.videoFlag = false
          }
        }
      }, (err, data) => {
        if (err) {
          const errorRes = {
            msg: "上传错误",
          }
          this.handleUploadSuccess(errorRes, file)
        } else {
          const res = {
            code: 200,
            data: {
              fileName: aliyunFileKey
            }
          }
          this.handleUploadSuccess(res, file)
        }
      })
      /* let file = e.file // 文件信息
      if (!file) {
        return false
      }
      let date = moment().format("YYYY-MM-DD")
      let aliyunFileKey = this.model + '/' + date  + '/' + new Date().getTime() + parseInt(Math.random() * ( 9999 - 1000 + 1 ) + 1000, 10) ;
      OSSClient.put(aliyunFileKey, file).then(uploadRes => {
        const name = uploadRes.name;
        const res = uploadRes.res;
        if (res.status === 200) {
          const res = {
            code: 200,
            data: {
              fileName: name
            }
          }
          this.handleUploadSuccess(res, file);
        } else {
          const errorRes = {
            msg: "上传错误",
          }
          this.handleUploadSuccess(errorRes, file);
        }
      }) */
    },
    // 上传前校检格式和大小
    handleBeforeUpload (file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.')
        const fileExt = fileName[fileName.length - 1]
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`)
          return false
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
      return true
    },
    handleRemove (file, fileList) {
      this.$emit("input", this.listToString(fileList))
    },
    handlePreview (file) {
      file.status == 'success' && open(this.$yun.getPreviewUrl(file.previewUrl))
    },
    handleExceed (files, fileList) {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`)
    },
    beforeRemove (file, fileList) {
    },
    // 上传失败
    handleUploadError (err, file, fileList) {
      console.log("error", fileList)
      this.$modal.msgError("上传文件失败，请重试")
      this.$modal.closeLoading()
    },
    handleUploadSuccess (res, file, fileList) {
      console.log('----------', file)
      if (res.code === 200) {
        file.previewUrl = res.data.fileName

      } else {
        this.$yun.listRemoveForCondition(fileList, i => {
          return i.uid == file.uid
        })
        this.$modal.msgError(res.msg)
      }
      let fileList1 = []
      fileList1.push(
        { name: file.name, url: res.data.fileName }
      )
      console.log(fileList1)
      this.$emit("input", fileList1[0])
    },
    handleProgress (event, file, fileList) {
    },
    handleChange (file, fileList) {
      // this.handleImport(file.raw)
    },
    handleImport (file) {
      var that = this
      const api = '/WebService.asmx/FileAdd'
      let formData = new FormData()
      formData.append('file[0]', file)
      axios({
        method: 'post',
        url: api,
        data: formData,
        onUploadProgress: function (progressEvent) { //原生获取上传进度的事件
          if (progressEvent.lengthComputable) {
            that.progressFlag = true // 显示进度条
            that.loadProgress = parseInt(progressEvent.loaded / progressEvent.total * 100) // 动态获取文件上传进度
            if (that.loadProgress >= 100) {
              that.loadProgress = 100
              setTimeout(() => {
                that.progressFlag = false
              }, 1000) // 一秒后关闭进度条
            }
          }
        },
      }).then((res) => {
        console.log(res.data)
        if (res.data == '新增媒体文件成功') {
          that.$message({
            message: '新增媒体文件成功',
            type: 'success'
          })
          that.dialogVisible = false
          that.$emit('getdata', 0)
        } else {
          that.$message.error(res.data)
        }
      })
    },
    listToString (list, separator) {
      let strs = ""
      separator = separator || ","
      for (let i in list) {
        strs += list[i].previewUrl + separator
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : ''
    },
  }
}
</script>
